import {
    ADD_BAR,
    BAR_LIST,
    CURRENT_BAR,
    DEL_All_BAR,
    DEL_BAR,
    SET_BAR_LIST,
    SET_CURRENT_BAR,
} from "@/store/modules/tabbar/type";

const index = {
    namespaced: true,
    state: {
        moreMenuList: [],
        barList: JSON.parse(sessionStorage.getItem(BAR_LIST)) || [],
        currentBar: JSON.parse(sessionStorage.getItem(CURRENT_BAR)) || {},
    },
    mutations: {
        [SET_BAR_LIST](state, data) {
            state.barList = data;
        },
        [SET_CURRENT_BAR](state, currentBar) {
            state.currentBar = currentBar;
            sessionStorage.setItem(
                CURRENT_BAR,
                JSON.stringify(state.currentBar),
            );
        },
        [ADD_BAR](state, content) {
            // 不允许重复，每个标签只允许存在一个
            // let ind = state.barList.findIndex(el => el.key === content.key)
            // if(ind == -1) {
            //     state.barList.push(content)
            // }
            // sessionStorage.setItem(BAR_LIST, JSON.stringify(state.barList));
            // 每个标签都可以重复打开多个
            // content.index = state.barList.length;

            if (state.moreMenuList.includes(content.barCode)) {
                state.barList.push(content);
            } else {
                let ind = state.barList.findIndex(
                    (el) => el.barCode === content.barCode,
                );
                if (ind === -1) {
                    state.barList.push(content);
                } else {
                    console.log("重复：" + content.barName);
                }
            }

            sessionStorage.setItem(BAR_LIST, JSON.stringify(state.barList));

            // 防止重复 对象不一致

            state.currentBar = state.barList.filter(
                (item) => item.barCode === content.barCode,
            )[0];
            sessionStorage.setItem(
                CURRENT_BAR,
                JSON.stringify(state.currentBar),
            );
        },
        [DEL_BAR](state, barCode) {
            console.log("删除之前" + state.barList.length);
            state.barList = state.barList.filter(
                (item) => item.barCode !== barCode,
            );
            console.log("删除之后" + state.barList.length);
            sessionStorage.setItem(BAR_LIST, JSON.stringify(state.barList));
        },
        [DEL_All_BAR](state, content) {
            state.barList = content || [{ keyPath: "/home", key: "Home" }];
            sessionStorage.setItem(BAR_LIST, JSON.stringify(state.barList));
        },
    },
    actions: {
        [ADD_BAR]({ commit }, content) {
            commit(ADD_BAR, content);
        },
        [DEL_BAR]({ commit }, barCode) {
            commit(DEL_BAR, barCode);
        },
        [SET_CURRENT_BAR]({ commit }, currentBar) {
            commit(SET_CURRENT_BAR, currentBar);
        },
    },
};

export default index;
